<template>
  <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="80%" top="5vh">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="dialog_height">
      <el-form-item label="场地名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入场地名称" />
      </el-form-item>
  
      <el-form-item label="地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入地址" />
      </el-form-item>
  
      <!-- <el-form-item label="营业时间" prop="openingHours">
            <el-input v-model="formData.openingHours" placeholder="请输入营业时间" />
          </el-form-item> -->
      <el-form-item label="营业时间">
        <el-col :span="11">
          <el-form-item prop="startTime">
            <el-time-select :picker-options="{
        start: '00:00',
        step: '00:15',
        end: '23:59'
      }" v-model="formData.startTime" value-format="HH:mm" placeholder="开始时间" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="2" class="text-center">至</el-col>
        <el-col :span="11">
          <el-form-item prop="endTime">
            <el-time-select :picker-options="{
        start: '00:00',
        step: '00:15',
        end: '23:59'
      }" v-model="formData.endTime" value-format="HH:mm:ss" placeholder="结束时间" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-form-item>
  
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input v-model="formData.phoneNumber" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="封面图片" prop="coverImage">
        <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
          :on-success="handleIconSuccess" :before-upload="beforeImageUpload">
          <img v-if="formData.coverImage" :src="formData.coverImage" class="uploaded-image" />
          <div v-else class="upload-placeholder">
            <i class="el-icon-plus"></i>
            <div class="upload-text">点击上传封面图片</div>
          </div>
        </el-upload>
        <!-- <div class="form-tip">建议尺寸：200x200px，支持jpg、png格式</div> -->
      </el-form-item>
      <el-form-item label="轮播图片" prop="logo">
        <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
          :on-success="handleIconSuccess1" :before-upload="beforeImageUpload">
          <div class="flex_flex">
            <div v-for="item,index in formData.imageUrl" :key="index" class="image-item">
              <img :src="item" class="uploaded-image" />
              <div class="delete-image" @click="handleDeleteImage(index)">删除</div>
            </div>
            <div class="upload-placeholder">
              <i class="el-icon-plus"></i>
              <div class="upload-text">点击上传图片</div>
            </div>
          </div>
        </el-upload>
      </el-form-item>
  
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">下架</el-radio>
          <el-radio :label="1">上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="场地描述" prop="description">
        <EditorBar style="width: 100%" v-model="formData.description" :catchData="catchDataAgreement"></EditorBar>
      </el-form-item>
    </el-form>
  
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import EditorBar from "@/components/WangEnduit.vue";
export default {
  name: 'SiteDialog',
  components: {
    EditorBar
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => ({})
    }
  },

  data() {
    return {
      headers: {
        'token': localStorage.getItem('token')
      },
      formData: {
        // id: undefined,
        name: '',
        // venueCategory: undefined,
        address: '',
        // openingHours: '',
        phoneNumber: '',
        description: '',
        coverImage: '',
        status: 1,
        imageUrl: [],
        startTime: '09:30',
        endTime: '21:30',
      },
      fileKey: '',
      action: '',
      coverImage: '',
      rules: {
        name: [{ required: true, message: '请输入场地名称', trigger: 'blur' }],
        // venueCategory: [{ required: true, message: '请选择场地分类', trigger: 'change' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        description: [{ required: true, message: '请输入场地描述', trigger: 'blur' }]
      }
    }
  },

  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    dialogTitle() {
      return this.formData.id ? '编辑场地' : '新增场地'
    }
  },

  watch: {
    editData: {
      handler(val) {
        if (val && Object.keys(val).length) {
          this.formData = { ...val }
        } else {
          this.formData = {
            // id: undefined,
            name: '',
            // venueCategory: undefined,
            address: '',
            // openingHours: '',
            phoneNumber: '',
            description: '',
            coverImage: '',
            status: 1,
            imageUrl: [],
            startTime: '09:30',
            endTime: '21:30',
          }
        }
      },
      immediate: true,
      deep: true
    }
  },

  methods: {
    //基本信息富文本编辑
    catchDataAgreement(val) {
      this.formData.description = val;
    },
    handleDeleteImage(index) {
      this.formData.imageUrl.splice(index, 1)
    },
    // 图片上传成功回调
    async handleIconSuccess1(res) {
      this.formData.imageUrl.push(res.result.filePath)
    },
    // 图片上传成功回调
    async handleIconSuccess(res) {
      this.formData.coverImage = res.result.filePath
    },
    async beforeImageUpload(rawFile) {
      const imgSize = rawFile.size / 1024 / 1024 < 10
      const imgType = ['image/jpeg', 'image/png', 'image/gif']
      if (!imgType.includes(rawFile.type))
        message.notifyWarning('上传图片不符合所需的格式！')
      if (!imgSize) message.notifyWarning(`上传图片大小不能超过 10M！`)
      return imgType.includes(rawFile.type) && imgSize
    },

    // 图片上传前的校验
    beforeAvatarUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJpgOrPng) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJpgOrPng && isLt2M
    },

    // 取消
    handleCancel() {
      this.dialogVisible = false
    },

    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            // const api = this.formData.id ? 'updateSite' : 'createSite'
            // await this.$api[api](this.formData)
            let data = {}
            const params = {
              ...this.formData,
              //   coverImage: this.coverImage
            }
            console.log(params, 'params');
            if (this.formData.id) {
              data = await this.$api.editSite(params)
            } else {
              data = await this.$api.addSite(params)
            }

            this.$message.success(`${this.formData.id ? '编辑' : '新增'}成功`)
            this.$emit('success')
            this.dialogVisible = false
          } catch (error) {
            console.error(error)
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.text-center {
  text-align: center;
}

.image-item {
  position: relative;
}

.delete-image {
  position: absolute;
  bottom: 15px;
  right: 0px;
  width: 100%;
  height: 20px;
  font-size: 14px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  cursor: pointer;
  z-index: 1000;
  line-height: 20px;
}

.flex_flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-uploader {
  .uploaded-image {
    width: 140px;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
  }

  .upload-placeholder {
    width: 140px;
    height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
      margin-top: 8px;
    }
  }
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>